#import "RPNetworkTool.h"
@implementation RPNetworkTool

#pragma mark - 单例

+ (instancetype)sharedTool{
     
    static dispatch_once_t onceToken;
    
    static RPNetworkTool *instance;
    
    dispatch_once(&onceToken, ^{
        instance = [[super alloc]init];
        instance.responseSerializer = [AFJSONResponseSerializer serializer];
        AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
        requestSerializer.timeoutInterval = 180;

        [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
       
        instance.requestSerializer = requestSerializer;
        
        ///2.获取AFN原有的数据解析类型 然后新增一些响应解析器能够接受的数据类型
        NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:instance.responseSerializer.acceptableContentTypes];
        [acceptableContentTypes addObjectsFromArray:@[@"application/json", @"text/json", @"text/javascript",@"text/html",@"plant/html",@"text/plain",@"text/xml",@"multipart/form-data"]];
        instance.responseSerializer.acceptableContentTypes = acceptableContentTypes;
    });
    return instance;
}

+ (NSString *)getRequestURLWithAPI:(NSString *)api{
    return [NSString stringWithFormat:@"%@%@",BaseUrl,api];
}

#pragma mark - 自定义GET
- (void)requestGET:(NSString *)URLString parames:(id)parames success:(void (^)(id responseObj))success failure:(void (^)(id error))failure{
    [self GET:URLString parameters:parames headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];

}

 #pragma mark - 自定义POST
- (NSURLSessionTask *)requestPOST:(NSString *)URLString parames:(id)parames success:(void (^)(id responseObj))success failure:(void (^)(id error))failure{
   
    NSLog(@"\n%@\n%@",URLString,parames);
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:URLString parameters:nil error:nil];
    if (parames != nil) {
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:parames];
        NSData *jsonData = [param mj_JSONData];
        [request setHTTPBody:jsonData];
    }
    
    NSURLSessionTask *task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error) {
            failure(error);
        }else{
            if ([responseObject[@"code"] intValue] == 1) {
                success(responseObject);
            }else{
                failure(error);
            }
            
        }
    }];    
    [task resume];
    
    return task;
 }
#pragma mark - 上传数据
- (void)uploadWithURLString:(NSString *)URLString parameters:(id)parameters uploadParam:(NSArray<RNNetworkParam *> *)uploadParams success:(void (^)(id responseObj))success failure:(void (^)(NSError *))failure{
    [self POST:URLString parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (RNNetworkParam *param in uploadParams) {
            [formData appendPartWithFileData:param.data name:param.name fileName:param.filename mimeType:param.mimeType];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] intValue] == 1) {
            success(responseObject);
        }else{
            [SVProgressHUD dismiss];
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:@"上传失败..." duration:2 finishHandler:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:@"上传失败..." duration:2 finishHandler:nil];
        failure(error);
    }];
}


#pragma mark - 下载数据

- (void)downLoadWithURLString:(NSString *)URLString parameters:(id)parameters progerss:(void (^)(void))progress success:(void (^)(void))success failure:(void (^)(NSError *))failure{
    NSURLRequest *requeset = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];

    NSURLSessionDownloadTask *downTask = [self downloadTaskWithRequest:requeset progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return targetPath;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        failure(error);
    }];
    [downTask resume];
}
@end
